package listeners;

import gui.MainFrame;
import gui.MyTabbedPane;
import gui.ChatTab;

import java.awt.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;
import javax.swing.JPanel;

import model.User;

public class MDBListener implements MessageListener {
	
	private ChatTab chatTab;
	private MyTabbedPane mtp;

	public MDBListener(Session session, Topic topic) {
		connect(session, topic);
	}

	@Override
	public void onMessage(Message arg0) {
		// TODO Auto-generated method stub
		if(mtp==null) {
			mtp=MainFrame.getInstance().getTabbedPane();
		}
		if(arg0 instanceof ObjectMessage) {
			ObjectMessage objMsg = (ObjectMessage) arg0;
			model.Message poruka = null;
			try {
				poruka = (model.Message) objMsg.getObject();
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			User from = poruka.getFrom();
			User to = poruka.getTo();
			
			if(from==MainFrame.getInstance().getCurrentUser())
				return;
			
			if(to==null) {
				mtp.getChatTabs().get(0).displayMessage(poruka);
			}
			else if(to.equals(MainFrame.getInstance().getCurrentUser())) {
				ChatTab ct = mtp.getTabWithUser(from);
				if(ct!=null) {
					ct.displayMessage(poruka);
				}
				else
				{
					int index=mtp.myAddTab("Chat with: "+from.toString(), new ChatTab(from));
					mtp.getChatTabs().get(index).displayMessage(poruka);
				}
			}
		}
	}
	
	public void connect(Session session,Topic topic) {
		MessageConsumer consumer;
		try {
			consumer = session.createConsumer(topic);
			consumer.setMessageListener(this);
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
